package cn.com.dycc.push;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;
import com.baidu.yun.push.auth.PushKeyPair;
import com.baidu.yun.push.client.BaiduPushClient;
import com.baidu.yun.push.constants.BaiduPushConstants;
import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.baidu.yun.push.model.PushBatchUniMsgRequest;
import com.baidu.yun.push.model.PushBatchUniMsgResponse;
import com.baidu.yun.push.model.PushMsgToAllRequest;
import com.baidu.yun.push.model.PushMsgToAllResponse;
import com.baidu.yun.push.model.PushMsgToSingleDeviceRequest;
import com.baidu.yun.push.model.PushMsgToSingleDeviceResponse;

import cn.com.dycc.util.PropertiesUtil;
import net.sf.json.JSONObject;

/**
 * 百度云推送 
 * @author linfa
 *
 */
public class BaiduPush {
	
	
	 /**
     * 推送初始化
     * @return
	 * @throws IOException 
     */
	private static BaiduPushClient initPushClient() throws IOException{
    	
		String apiKey = PropertiesUtil.readProperties("apiKey");
		String secretKey = PropertiesUtil.readProperties("secretKey");
		System.out.println(apiKey+secretKey);
		
        //手机标识
//      Integer deviceType = 3;
//      Integer deviceType = request.getSession().getAttribute("deviceType");
		
//      if (deviceType != null && deviceType.intValue() == 4) { //ios
//          apiKey = key.getApiKey();
//          secretKey = key.getSecretKey();
//      }else if(deviceType==3){//Android
//          apiKey = key.getApiKey();
//          secretKey = key.getSecretKey();
//      }
    	
        // 1.从开发人员控制台获取apiKey和secretKey
        PushKeyPair pair = null;
        pair = new PushKeyPair(apiKey,secretKey);

        // 2.一个BaidupushClient对象来访问发布的接口
        BaiduPushClient pushClient = new BaiduPushClient(pair,BaiduPushConstants.CHANNEL_REST_URL);

        // 3.注册YunLogHandler，获取本次请求的交互信息
        pushClient.setChannelLogHandler(new YunLogHandler() {
           
            public void onHandle(YunLogEvent event) {
                System.out.println(event.getMessage());
            }
        });
        return  pushClient;
    }
	
	
	//单点推送
	public static String[] pushNotificationByUser(String channelId,Integer deviceType,JSONObject notification) throws IOException{
		 
        String[] results = new String[3];
        String retCode = "1";
        String retMsg = "成功";
		
        BaiduPushClient pushClient =  BaiduPush.initPushClient();
        
//        JSONObject notification = new JSONObject();
//        notification.put("title", "测试");
//        notification.put("description",message);
//        notification.put("notification_builder_id", 0);
//        notification.put("notification_basic_style", 4);
//        notification.put("open_type", 1);
// //     notification.put("url", "http://push.baidu.com");//app上点开推送之后跳转的链接
// //       System.out.println("21");
////      JSONObject jsonCustormCont = new JSONObject();
////      jsonCustormCont.put("name", "test"); //自定义内容，key-value
////      notification.put("custom_content", jsonCustormCont);
        try {
//        	 System.out.println("1");
        	 PushMsgToSingleDeviceRequest request = new PushMsgToSingleDeviceRequest();
        	 request.addChannelId(channelId);
        	 request.addMsgExpires(new Integer(3600));// message有效时间
             request.addMessageType(0);// 1：通知,0:透传消息. 默认为0 注：IOS只有通知.
             request.addMessage(notification.toString());
             request.addDeviceType(deviceType);// deviceType => 3:android, 4:ios
             
             // 5. 执行Http请求
             PushMsgToSingleDeviceResponse response = pushClient.pushMsgToSingleDevice(request);
             // 6. 认证推送成功
//             System.out.println("cs2="+"1");
             System.out.println("msgId: " + response.getMsgId()+ ",sendTime: " + response.getSendTime());
             
             
		} catch (PushClientException e) {
            //ERROROPTTYPE 用于设置异常的处理方式 -- 抛出异常和捕获异常,
            //'true' 表示抛出, 'false' 表示捕获。
            if (BaiduPushConstants.ERROROPTTYPE) { 
                try {
                    throw e;
                } catch (PushClientException e1) {
                    e1.printStackTrace();
                }
            } else {
                e.printStackTrace();
            }
        } catch (PushServerException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                try {
                    throw e;
                } catch (PushServerException e1) {
                    e1.printStackTrace();
                }
            } else {
                System.out.println("params = "+String.format(
                        "requestId: %d, errorCode: %d, errorMsg: %s",
                        e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
            }
            
        }finally {
            results[0] = retCode;
            results[1] = retMsg;
        }
       
		  return results;
	  }
	
	 //批量单推 不支持ios
	 public static String[] pushBatchUniMsg(String[] channelIds,JSONObject notification,Integer deviceType) throws PushServerException, PushClientException,IOException{
		 
		 String[] results = new String[3];
	     String retCode = "1";
	     String retMsg = "成功！";
		 
	     BaiduPushClient pushClient =  BaiduPush.initPushClient();
		 
	        try {
	            // 指定请求参数
//	            String[] channelIds = { "xxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxx" };
	            PushBatchUniMsgRequest request = new PushBatchUniMsgRequest()
	                    .addChannelIds(channelIds)
	                    .addMsgExpires(new Integer(3600))
	                    .addMessageType(0).// 1：通知,0:透传消息. 默认为0 注：IOS只有通知.
                        addMessage(notification.toString()).
	                    addDeviceType(deviceType); //.addTopicId("BaiduPush");// 设置类别主题
	            // 5. 执行Http请求
	            PushBatchUniMsgResponse response = pushClient
	                    .pushBatchUniMsg(request);
	            // Http请求返回值解析
	            System.out.println(String.format("msgId: %s, sendTime: %d",
	                    response.getMsgId(), response.getSendTime()));
	        } catch (PushClientException e) {
	            if (BaiduPushConstants.ERROROPTTYPE) {
	                throw e;
	            } else {
	                e.printStackTrace();
	            }
	        } catch (PushServerException e) {
	            if (BaiduPushConstants.ERROROPTTYPE) {
	                throw e;
	            } else {
	                System.out.println(String.format(
	                        "requestId: %d, errorCode: %d, errorMsg: %s",
	                        e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
	            }
	        }finally {
	            results[0] = retCode;
	            results[1] = retMsg;
	        }
		 
		 return results;
	 }
	 
	 //广播推送
	 public static String[] pushMsgToAll(JSONObject notification,Integer deviceType) throws PushClientException, PushServerException, IOException{
	     
		 String[] results = new String[3];
	     String retCode = "1";
	     String retMsg = "成功！";
		 
		 BaiduPushClient pushClient = initPushClient();
		//获取时间戳
		 Date date = new Date();
		 Long time = date.getTime();
		 
		 
		 
	     try {
	    	 // 4.指定请求参数
	    	 PushMsgToAllRequest request = new PushMsgToAllRequest();
//	            .addMsgExpires(new Integer(3600)) //默认 new Integer(3600)
//	            .addMessageType(0) // 0:透传消息  1：通知  默认是 0
//	            .addMessage(notification.toString())//添加透传消息
//	            .addSendTime(System.currentTimeMillis() / 1000 + 70) // 设置定时推送时间，必需超过当前时间一分钟，单位秒.实例2分钟后推送   System.currentTimeMillis() / 1000 + 120
//	            .addDeviceType(deviceType);
	    	 	request.addDeviceType(deviceType);
	    	 	request.addMessageType(0);
	    	 	request.addMessage(notification.toString());
	    	 	request.addMsgExpires(new Integer(3600));
//	    	 	System.out.println("shij"+System.currentTimeMillis()/1000+70+"time="+time/1000);
	    	 	request.addSendTime(time/1000+120);
	    	 
	         
	            // 5. http request
	            PushMsgToAllResponse response = pushClient.pushMsgToAll(request);
	            // Http请求返回值解析
	            System.out.println("msgId: " + response.getMsgId() + ",sendTime: "    
	                    + response.getSendTime() + ",timerId: "
	                    + response.getTimerId());
	        } catch (PushClientException e) {
	            if (BaiduPushConstants.ERROROPTTYPE) {
	                throw e;
	            } else {
	                e.printStackTrace();
	            }
	        } catch (PushServerException e) {
	            if (BaiduPushConstants.ERROROPTTYPE) {
	                throw e;
	            } else {
	                System.out.println(String.format(
	                        "requestId: %d, errorCode: %d, errorMsg: %s",
	                        e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
	            }
	        }finally{
            	results[0] = retCode;
 	            results[1] = retMsg;
            }
	        
	        return results;
	 }
	 
		
	
	  public static void main(String[] args) {
	     BaiduPush baiduPush = new BaiduPush();
	     Map<String, Object> map = new HashMap<String, Object>();
	     //       String apiKey = "aYrgyhu7hoqyUtENEZVyFBWb";
	     //       String secretKey = "Img5mFzC07Sh5AEVC6GhHNsXGc3rG4hP";
	     //       deviceType = 3;
	     //       message = "这是条测试推送信息2！"; 
//	     baiduPush.pushNotificationByUser("4019688486852140065", 3, "今天天气不错",map);
	  }
	   
	   
	  
	   
	   
	   
	   
	   
}
